﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Common;
using WebSite.Core;
using System.Net;

namespace WebSite.Server
{
    /// <summary>
    /// GeneratePhoneCode 的摘要说明
    /// </summary>
    public class GeneratePhoneCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest( HttpContext context )
        {
            context.Response.ContentType = "text/json";
            

            RetInfo response = RetInfoHelper.WebServiceReturn( delegate()
            {
                string phone = context.Request["phone"] ?? "";
                long p = 0;

                if (!long.TryParse( context.Request["phone"], out p ))
                {
                    throw new RuntimeException( 2, "手机号码无效" );
                }

                if (p.ToString().Length != 11)
                {
                    throw new RuntimeException( 2, "手机号码无效，必须11位" );
                }

                if (!p.ToString().StartsWith( "13" ) && !p.ToString().StartsWith( "18" ) && !p.ToString().StartsWith( "15" ))
                {
                    throw new RuntimeException( 2, "手机号码无效，必须是13/15/18开头" );
                }

                if (context.Cache["Phone_" + p.ToString()] != null)
                {
                    throw new RuntimeException( 2, "请勿频繁发送验证短信请求，1分钟内只能发送一次" );
                }
                context.Cache.Insert( "Phone_" + p.ToString(), true, null, DateTime.Now.AddMinutes( 1 ), System.Web.Caching.Cache.NoSlidingExpiration );

                const string url = "http://php.ydon.cn/jlf/one.php?p={0}&s={1}";

                Random r = new Random();
                int randcode = r.Next( 0, 10000 );

                string codestr = string.Format("{0:d4}", randcode );

                context.Session["reg_phone"] = p.ToString();
                context.Session["reg_code"] = codestr;

                const string msg = "感谢您注册家乐福“冠军宝贝在我家—2013快乐宝宝帮大赛”，您的验证码为：{0}，该验证码有效期5分钟";

                WebClient client = new WebClient();
                client.DownloadString( string.Format( url, p.ToString(), HttpUtility.UrlEncode( string.Format( msg, codestr ) ) ) );

                // context.Cache.Insert(

                return true;
            });

            context.Response.Write( response.SerializeToString( Common.Serialization.SerializationType.Json ) );
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}